package com.crazy.boot.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.crazy.boot.entity.Role;
import com.crazy.boot.entity.User;
import com.crazy.boot.service.UserService;

public class CustomerRealm extends AuthorizingRealm{
	
	static Logger logger = LoggerFactory.getLogger(AuthorizingRealm.class);
	
	@Autowired
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		logger.info("-------------开始授权--------------");
		String userName = (String) principals.getPrimaryPrincipal();
		User user = userService.getUserByName(userName);
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		System.out.println(user);
		if(user != null) {
			List<Role> rList = user.getRList();
			for(Role r : rList) {
				authorizationInfo.addRole(r.getRoleKye());
			}
		}
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) 
			throws AuthenticationException {
		// logger.info("-------------开始认证--------------");
		String userName = (String)token.getPrincipal();
		User user = userService.getUserByName(userName);
		if(user != null) {
			// logger.info("-------------认证结束--------------");
			return new SimpleAuthenticationInfo(
					userName,
					user.getPassword(),
					ByteSource.Util.bytes(user.getSalt()),
					this.getName()
					);
		}
		return null;
	}
}